//
//  PlayVoiceView.m
//  GC_OC
//
//  Created by 曾 on 2022/2/15.
//  

#import "PlayVoiceView.h"
#import "PlayVoiceSubtitleView.h"
#import <MediaPlayer/MediaPlayer.h>
#import "PlayModel.h"
#import "PlayMulitpleView.h"
@interface PlayVoiceView()<WKUIDelegate,WKNavigationDelegate>

@property (nonatomic, strong)ObjectAFNetWorking* objectAFN;
@property (nonatomic, strong)UIView*       backView;
@property (nonatomic, strong)PlayModel*    model;
@property (nonatomic, strong)NSDictionary* dic;
@property (nonatomic, strong)UILabel*      tipLabel;
@property (nonatomic, strong)UIButton*     videoBtn;
@property (nonatomic, strong)UIView*       backebView;

@property (nonatomic, strong)WKWebView*   wkwebView;
@property (nonatomic, strong)NSMutableArray* btnArr;
@property (nonatomic, strong)UIScrollView* scrollView;
@property (nonatomic, strong)UISlider*     slider;
@property (nonatomic, strong)UILabel*      startLabel;
@property (nonatomic, strong)UILabel*      endLabel;
@property (nonatomic, strong)UILabel*      timerLabel;

/**倍数0=0.5 1=1.0 2=1.25 3=1.5 4=2.0 5=*/
//array=@[@"0.5",@"1.0",@"1.25",@"1.5",@"2.0",@"2.5",@"3.0"]
@property (nonatomic, strong)NSArray*      mulitpleArr;
@property (nonatomic, assign)NSInteger     mulitpleType;
//@property (nonatomic, assign)NSInteger

@property (nonatomic, assign)BOOL         subtitle;
@property (nonatomic, strong)PlayVoiceSubtitleView* playsubtitleView;

/**是不是在直播*/
@property (nonatomic, assign)BOOL isplayer;
@property (nonatomic, strong)AVPlayer               *player;
@property (nonatomic, strong)AVPlayerItem           *item;
@property (nonatomic, strong)id                     infotu;
@property (nonatomic, strong)MPNowPlayingInfoCenter *playingCenter;
@property (nonatomic, strong)NSMutableDictionary    *playingInfo;
/**播放时长*/
@property (nonatomic, assign)CGFloat                 allPlayVolumes;
@property (nonatomic, assign)CGFloat                 nowPlayTime;
@property (nonatomic, strong)NSTimer*                timer;
@property (nonatomic, strong)UIImageView*            loadImagView;
@property (nonatomic, strong)UIButton*               playBtn;

@property (nonatomic, strong) CurriculumModel *currentSong;
@end

@implementation PlayVoiceView
-(instancetype)initWithFrame:(CGRect)frame andDic:(NSDictionary*)dic
{
    self=[super initWithFrame:frame];
    if(self)
    {
        self.btnArr=[NSMutableArray new];
        self.mulitpleArr=@[@"0.5",@"1.0",@"1.25",@"1.5",@"2.0",@"2.5",@"3.0"];
        self.mulitpleType=[[NSUserDefaults standardUserDefaults]integerForKey:@"mulitpleType"];
        self.model=[PlayModel sharedModel];
        self.objectAFN=[[ObjectAFNetWorking alloc]init];
        [self setBackPlay];
        [self initView];
    }
    return self;
}
/**设置背后播放*/
-(void)setBackPlay
{
    MPRemoteCommandCenter *commandCenter = [MPRemoteCommandCenter sharedCommandCenter];
    commandCenter.playCommand.enabled=YES;
    [commandCenter.playCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        [self playPlayer];
        return MPRemoteCommandHandlerStatusSuccess;
    }];
    commandCenter.pauseCommand.enabled=YES;
    [commandCenter.pauseCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        [self stopPlayer];
        return MPRemoteCommandHandlerStatusSuccess;
    }];
    commandCenter.previousTrackCommand.enabled=YES;
    [commandCenter.previousTrackCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        [self previousPlayer];
        return MPRemoteCommandHandlerStatusSuccess;
    }];
    commandCenter.nextTrackCommand.enabled=YES;
    [commandCenter.nextTrackCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        [self nextPlayer];
        return MPRemoteCommandHandlerStatusSuccess;
    }];
    commandCenter.togglePlayPauseCommand.enabled = YES;
    
    MPRemoteCommand* playPasuseCommand=commandCenter.togglePlayPauseCommand;
    playPasuseCommand.enabled=YES;
    [playPasuseCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
        if(self.isplayer)
        {
            [self stopPlayer];
        }else
        {
            [self player];
        }
        return MPRemoteCommandHandlerStatusSuccess;
    }];
    if(@available(iOS 9.1,*))
    {
        MPRemoteCommand* changePlaybackPositionCommand=commandCenter.changePlaybackPositionCommand;
        changePlaybackPositionCommand.enabled=YES;
        [commandCenter.changePlaybackPositionCommand addTargetWithHandler:^MPRemoteCommandHandlerStatus(MPRemoteCommandEvent * _Nonnull event) {
            MPChangePlaybackPositionCommandEvent* positionEvent=(MPChangePlaybackPositionCommandEvent* )event;
            if(self.dic)
            {
                [self Progress:positionEvent.positionTime];
            }else
            {
                return MPRemoteCommandHandlerStatusCommandFailed;
            }
            return MPRemoteCommandHandlerStatusSuccess;
        }];
    }
    self.playingCenter=[MPNowPlayingInfoCenter defaultCenter];
    self.playingInfo=[NSMutableDictionary new];
     NSInteger  playTimeAction=[[NSUserDefaults standardUserDefaults] integerForKey:@"palyTimeType"];
    [self playTimeAction:playTimeAction];
}
/**定时关闭*/
-(void)playTimeAction:(NSInteger)playTimeType
{
    [_timer invalidate];
    _timer=nil;
    NSArray* array=@[@15,@30,@60,@90,@120];
    _timer=[NSTimer scheduledTimerWithTimeInterval:[array[playTimeType] integerValue]*60 target:self selector:@selector(stopPlayer) userInfo:nil repeats:NO];
}
-(AVPlayer*)player
{
    if(!_player)
    {
        _player=[[AVPlayer alloc]init];
    }
    return _player;
}

- (void)stopPlayer
{
    self.isplayer = false;
    [_player pause];
    [self refreshPlayUI];
    if (@available(iOS 13.0, *)) {
        self.playingCenter.playbackState=MPNowPlayingPlaybackStateStopped;
    } else {
    }
}

-(void)playPlayer
{
    self.isplayer=YES;
    [_player play];
    [self refreshPlayUI];
    if (@available(iOS 13.0, *)) {
        self.playingCenter.playbackState=MPNowPlayingPlaybackStatePlaying;
    } else {
    }
}
-(void)cureePlayer
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    //当前播放数组 当前播放下标
    if(_item)
    {
        [_item removeObserver:self forKeyPath:@"status"];
        [_item removeObserver:self forKeyPath:@"loadedTimeRanges"];
        _item=nil;
    }
    if(_player)
    {
        [_player.currentItem cancelPendingSeeks];
        [_player.currentItem.asset cancelLoading];
        [_player removeTimeObserver:_infotu];
        _infotu=nil;
        _player=nil;
    }
    NSString *audioUrl = self.dic[@"data"][@"audio_url"];
    BOOL isChaine = [self hasChinese:audioUrl];
    if (isChaine) {
        audioUrl = [audioUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    }
    NSURL* url=[NSURL URLWithString:audioUrl];
    _item=[[AVPlayerItem alloc]initWithURL:url];
    [_item addObserver:self forKeyPath:@"status" options:(NSKeyValueObservingOptionNew) context:nil];
    [_item addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
    [self.player replaceCurrentItemWithPlayerItem:_item];
    [self playPlayer];
    [self monitoringPlayback:_item];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playbackFinished:) name:AVPlayerItemDidPlayToEndTimeNotification object:_player.currentItem];
    UIImage* coverImage=[UIImage imageNamed:@"Logo"];
    MPMediaItemArtwork* artowk=[[MPMediaItemArtwork alloc]initWithImage:coverImage];
    self.playingInfo[MPMediaItemPropertyArtwork]=artowk;
    if(self.dic[@"image"])
    {
        [self.loadImagView sd_setImageWithURL:[NSURL URLWithString:self.dic[@"data"][@"image"]] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
            NSLog(@"我走了这里");
            if(!image)
            {
                image = [UIImage new];
                image=[UIImage imageNamed:@"logo"];
            }
            MPMediaItemArtwork* artowk=[[MPMediaItemArtwork alloc]initWithImage:image];
            self.playingInfo[MPMediaItemPropertyArtwork]=artowk;
            [self.playingCenter setNowPlayingInfo:self.playingInfo];
        }];

    }
    self.playingInfo[MPMediaItemPropertyArtist]=@"小众";
    self.playingInfo[MPMediaItemPropertyTitle]=self.dic[@"data"][@"name"];
    self.playingInfo[MPMediaItemPropertyAlbumTitle]=self.dic[@"data"][@"describe"];
    [self.playingCenter setNowPlayingInfo:self.playingInfo];
}
- (BOOL)hasChinese:(NSString *)str {
    for(int i=0; i< [str length];i++){
        int a = [str characterAtIndex:i];
        if( a > 0x4e00 && a < 0x9fff)
        {
            return YES;
        }
    }
    return NO;
}
#pragma mark KVO - status  当缓存也走这里
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    if(![self.item isEqual:object])
    {
        return;
    }
    if ([keyPath isEqualToString:@"status"])
    {
        AVPlayerStatus status = [[change objectForKey:@"new"] intValue]; // 获取更改后的状态
        if (status == AVPlayerStatusReadyToPlay)
        {
            CMTime duration =_player.currentItem.asset.duration;
            if(CMTimeGetSeconds(duration))
            {
               if(self.isplayer)
               {
                   [_player play];
               }
            }
            if(CMTimeGetSeconds(duration))
            {
                self.allPlayVolumes=CMTimeGetSeconds(duration);
                self.endLabel.text=[GC_OCTool timeStrWithSecTime:self.allPlayVolumes];
            }
        }else if (status == AVPlayerStatusFailed)//播放失败
        {
            
        } else
        {
            
        }
    }else if([keyPath isEqualToString:@"loadedTimeRanges"])
    {
    }
}
//播放进度
- (void)monitoringPlayback:(AVPlayerItem *)item
{
    __weak typeof(self)WeakSelf = self;
    //播放进度, 每秒执行30次， CMTime 为30分之一秒
    _infotu=[_player addPeriodicTimeObserverForInterval:CMTimeMake(1,30.0) queue:dispatch_get_main_queue() usingBlock:^(CMTime time)
    {
        float currentPlayTime = (double)item.currentTime.value/ item.currentTime.timescale;
        if(currentPlayTime)
        {
            if(currentPlayTime>0)
            {
                CGFloat playValue=currentPlayTime/WeakSelf.allPlayVolumes*100;
                WeakSelf.nowPlayTime=currentPlayTime;
                playValue=ceilf(playValue)/100;
                CGFloat bfb=currentPlayTime/WeakSelf.allPlayVolumes;
                WeakSelf.slider.value=bfb;
                WeakSelf.playingInfo[MPNowPlayingInfoPropertyElapsedPlaybackTime]=[NSNumber numberWithFloat:WeakSelf.nowPlayTime];
                WeakSelf.playingInfo[MPMediaItemPropertyPlaybackDuration]=[NSNumber numberWithFloat:WeakSelf.allPlayVolumes];
                [WeakSelf.playingCenter setNowPlayingInfo:WeakSelf.playingInfo];
                WeakSelf.startLabel.text=[GC_OCTool timeStrWithSecTime:WeakSelf.nowPlayTime];
            }
        }
    }];
}
#pragma mark 播放完毕前台后台
-(void)playbackFinished:(NSNotification*)notification
{
    [self clearView];
    [[PlayModel sharedModel] playNextSong];
    [self refreshUI];
    [self refreshPlayUI];
    CurriculumModel *model = [[PlayModel sharedModel] currentModel];
    
    if([model.audio_num floatValue] > 0)
    {
        [self getData];
    }else
    {
        [self.myDelegate isVideoAction];
    }
}

/**上一首*/
-(void)previousPlayer
{
    [self clearView];
    [[PlayModel sharedModel] playLastSong];
    [self refreshUI];
    [self refreshPlayUI];
    CurriculumModel *model = [[PlayModel sharedModel] currentModel];
    
    if([model.audio_num floatValue] > 0)
    {
        [self getData];
    }else
    {
        [self.myDelegate isVideoAction];
    }
}

/**下一首*/
-(void)nextPlayer
{
    [self clearView];
    [[PlayModel sharedModel] playNextSong];
    [self refreshUI];
    [self refreshPlayUI];
    CurriculumModel *model = [[PlayModel sharedModel] currentModel];
    
    if([model.audio_num floatValue] > 0)
    {
        [self getData];
    }else
    {
        [self.myDelegate isVideoAction];
    }
}

/**快进*/
-(void)seekForwardPlayer:(UIButton*)sender
{
    CGFloat value=0.0;
    if(sender.tag==1000)
    {
       value=self.nowPlayTime+10;
    }else
    {
        value=self.nowPlayTime-10;
    }
    if(value<0)
    {
        value=0.0;
    }else if(value>self.allPlayVolumes)
    {
        value=self.allPlayVolumes;
    }
    [self Progress:value];
}
-(void)Progress:(CGFloat)progress;
{
    [_item seekToTime:CMTimeMakeWithSeconds(progress,1) toleranceBefore:kCMTimeZero toleranceAfter:kCMTimeZero completionHandler:^(BOOL finished) {
        [self playPlayer];
    }];
}
-(AVPlayerItem*)item
{
    if(!_item)
    {
        AVAsset* asset=[AVURLAsset URLAssetWithURL:[NSURL fileURLWithPath:self.dic[@"data"][@"audio_url"]] options:nil];
        _item=[AVPlayerItem playerItemWithAsset:asset];
    }
    return _item;
}

-(void)initView
{
   CGFloat height=[GC_OCTool getHeightForLabel:@"A" andFont:[UIFont boldSystemFontOfSize:FontSize(20)] andWidth:wid(100)];
    self.backView=[UIView new];
    [self addSubview:self.backView];
    
    UIView* view=[[UIView alloc]initWithFrame:CGRectMake(wid(25),hig(20),wid(5),height)];
    view.backgroundColor=RBG(58,139,231);

    UILabel* tipLabel=[[UILabel alloc]initWithFrame:CGRectMake(wid(45),hig(20),SCREEN_WIDTH-wid(30)-height-wid(45),height)];
    tipLabel.textColor=[UIColor whiteColor];
    tipLabel.font=[UIFont boldSystemFontOfSize:FontSize(20)];
    tipLabel.text=@"";
    self.tipLabel=tipLabel;
    [self addSubview:tipLabel];
    
    
    UIButton* btn=[[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-wid(25)-height,hig(20),height,height)];
    [btn setBackgroundImage:[UIImage imageNamed:@"视频"] forState:UIControlStateNormal];
    self.videoBtn=btn;
    [self addSubview:btn];
    CGFloat y=btn.y+btn.height+hig(35);

    
    self.backebView=[[UIView alloc]initWithFrame:CGRectMake(wid(25),0,SCREEN_WIDTH-wid(50),hig(350))];
    self.backebView.backgroundColor = [[UIColor whiteColor]colorWithAlphaComponent:0.1f];
    self.backebView.layer.maskedCorners=YES;
    self.backebView.layer.cornerRadius=hig(10);
    [self.backView addSubview:self.backebView];
    
    CGFloat btnWidth=SCREEN_WIDTH/3.0;
//    CGFloat btnHeight=hig()
    height=self.backebView.frame.origin.y+self.backebView.frame.size.height+hig(10);
    NSArray* textArr=@[@"自定义1",@"自定义1",@"自定义1",@"自定义1",@"自定义1",@"自定义1"];
    for(int i=0;i<6;i++)
    {
        NSInteger x=i%3;
        NSInteger y=i/3;
        UIButton* btn=[[UIButton alloc]initWithFrame:CGRectMake(x*btnWidth,height+y*hig(60),btnWidth,hig(60))];
        [btn setTitle:textArr[i] forState:UIControlStateNormal];
        [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        btn.titleLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:FontSize(14)];
        [self.btnArr addObject:btn];
        [self.backView addSubview:btn];
    }
    height+=hig(60)*2+hig(30);
    CGFloat tipWidth=[GC_OCTool getWidthForLabel:@"相关: " andFont:[UIFont fontWithName:@"Helvetica-Bold" size:FontSize(14)] andHeight:hig(100)];
    CGFloat tipHeight=[GC_OCTool getHeightForLabel:@"A" andFont:[UIFont fontWithName:@"Helvetica-Bold" size:FontSize(14)] andWidth:wid(100)];
    UILabel* lastLabel=[[UILabel alloc]initWithFrame:CGRectMake(wid(20),height,tipWidth,tipHeight)];
    lastLabel.text=@"相关: ";
    lastLabel.font=[UIFont fontWithName:@"Helvetica-Bold" size:FontSize(14)];
    lastLabel.textColor=[UIColor whiteColor];
    [self.backView addSubview:lastLabel];
    
    self.scrollView=[[UIScrollView alloc]initWithFrame:CGRectMake(tipWidth+wid(25),height,SCREEN_WIDTH-wid(25)-tipWidth,tipHeight)];
    [self.backView addSubview:self.scrollView];
    self.backView.frame=CGRectMake(0,y,SCREEN_WIDTH,self.scrollView.y+self.scrollView.height);
    
    
    height+=tipHeight+hig(20)+y;
    CGFloat jx=(SCREEN_WIDTH-wid(20)*2-hig(50)*5)/4.0;
    NSArray* iconImage=@[@"字幕关闭",@"定时器关闭",@"倍速1.0",@"下载",@"目录"];
    for (int i=0;i<5;i++)
    {
        UIButton* btn=[[UIButton alloc]initWithFrame:CGRectMake(wid(20)+i*(jx+hig(50)),height,hig(50),hig(50))];
        [btn setImage:[UIImage imageNamed:iconImage[i]] forState:UIControlStateNormal];
        btn.tag=400+i;
        [btn addTarget:self action:@selector(btnAction:) forControlEvents:UIControlEventTouchUpInside];
        if(i==1)
        {
            self.timerLabel=[[UILabel alloc]initWithFrame:CGRectMake(btn.x+btn.width+wid(5),btn.y,jx-wid(10), btn.height)];
            self.timerLabel.textColor=[UIColor whiteColor];
            self.timerLabel.adjustsFontSizeToFitWidth=YES;
            self.timerLabel.baselineAdjustment=UIBaselineAdjustmentAlignCenters;
            self.timerLabel.text=@"00:00";
            [self addSubview:self.timerLabel];
        }
        [self addSubview:btn];
    }
    height+=hig(70);
    UIButton* leftBtn=[[UIButton alloc]initWithFrame:CGRectMake(wid(20),height,hig(45),hig(45))];
    leftBtn.tag=999;
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"后退10秒"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(seekForwardPlayer:) forControlEvents:UIControlEventTouchUpInside];
    [self addSubview:leftBtn];
    UIButton* rightBtn=[[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH-wid(20)-hig(45),height,hig(45),hig(45))];
    rightBtn.tag=1000;
    [rightBtn addTarget:self action:@selector(seekForwardPlayer:) forControlEvents:UIControlEventTouchUpInside];
    [rightBtn setBackgroundImage:[UIImage imageNamed:@"前进10秒"] forState:UIControlStateNormal];
    [self addSubview:rightBtn];
    self.slider=[[UISlider alloc]initWithFrame:CGRectMake(wid(30)+hig(45),height,SCREEN_WIDTH-wid(60)-hig(90),hig(45))];
    [self addSubview:self.slider];
  CGFloat startHeight=[GC_OCTool getHeightForLabel:@"A" andFont:[UIFont systemFontOfSize:FontSize(10)] andWidth:wid(100)];
    self.startLabel=[[UILabel alloc]initWithFrame:CGRectMake(wid(30)+hig(45),height+hig(45),SCREEN_WIDTH/2.0,startHeight)];
    self.startLabel.font=[UIFont systemFontOfSize:FontSize(10)];
    self.startLabel.textColor=[UIColor whiteColor];
    self.startLabel.text=@"00:00";
    [self addSubview:_startLabel];
    self.endLabel=[[UILabel alloc]initWithFrame:CGRectMake(SCREEN_WIDTH- wid(30)-hig(45)-SCREEN_WIDTH/2.0,height+hig(45),SCREEN_WIDTH/2.0,startHeight)];
    self.endLabel.font=[UIFont systemFontOfSize:FontSize(10)];
    self.endLabel.textColor=[UIColor whiteColor];
    self.endLabel.textAlignment=NSTextAlignmentRight;
    self.endLabel.text=@"00:00";
    [self addSubview:self.endLabel];
    height+=hig(45)+hig(40);
    CGFloat lastjx=(SCREEN_WIDTH-hig(40)*4-hig(90))/6.0;
    CGFloat lastX=lastjx;
    NSInteger type=[[NSUserDefaults standardUserDefaults]integerForKey:@"playStyle"];
    NSArray* user=@[@"循环播放",@"单曲播放",@"随机播放"];
    NSArray* imageTextArr=@[user[type],@"上一首",@"播放",@"下一首",@"目录"];
    for(int i=0;i<5;i++)
    {
        UIButton* btn=[[UIButton alloc]initWithFrame:CGRectMake(lastX,height+(i==2?0:hig(40)/2.0),i==2?hig(90):hig(40),i==2?hig(90):hig(40))];
        lastX+=lastjx+btn.frame.size.width;
        [btn setBackgroundImage:[UIImage imageNamed:imageTextArr[i]] forState:UIControlStateNormal];
        btn.tag=600+i;
        [btn addTarget:self action:@selector(lastBtnAction:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:btn];
        if(i==2)
        {
            self.playBtn=btn;
        }
    }
}
-(WKWebView*)wkwebView
{
    if(!_wkwebView)
    {
        _wkwebView=[[WKWebView alloc]initWithFrame:CGRectMake(wid(10),hig(10),self.backebView.frame.size.width-wid(20),self.backebView.frame.size.height-hig(20))];
       _wkwebView.backgroundColor = [[UIColor whiteColor]colorWithAlphaComponent:0.0f];
       _wkwebView.scrollView.backgroundColor = [[UIColor whiteColor]colorWithAlphaComponent:0.0f];
       _wkwebView.scrollView.showsHorizontalScrollIndicator=false;
        _wkwebView.UIDelegate=self;
        _wkwebView.navigationDelegate=self;
       [_wkwebView setOpaque:NO];
        [self.backebView addSubview:_wkwebView];
    }
    return _wkwebView;
}

-(PlayVoiceSubtitleView*)playsubtitleView
{
    if(!_playsubtitleView)
    {
        _playsubtitleView=[[PlayVoiceSubtitleView alloc]initWithFrame:self.backView.frame];
        _playsubtitleView.alpha=0;
        [self addSubview:_playsubtitleView];
    }
    return _playsubtitleView;
}
/**刷新页面*/
-(void)refreshUI
{
    [self getData];
}

-(void)getData
{
    /**取消掉*/
    [_objectAFN cancelRequest];
    self.dic = nil;   //取消就清空

    NSString *filePath = [NSHomeDirectory() stringByAppendingString:[NSString stringWithFormat:@"/Documents/home_id%@_getcatedetail.json",self.currentSong.id]];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if ([fileManager fileExistsAtPath:filePath])
    {
        NSData* dataString=[NSData dataWithContentsOfFile:filePath];
        NSDictionary* lastdic=[NSJSONSerialization JSONObjectWithData:dataString options:NSJSONReadingMutableContainers error:nil];
        self.dic=lastdic;
        [self upDateView];
        [GC_OCTool saveFileAction:filePath];
    }else
    {
        [self.objectAFN getUrlStr:[NSString stringWithFormat:@"%@/api/home/getcatedetail?id=%@",server_addr,self.currentSong.id] finish:^(id  _Nonnull dataString) {
            NSDictionary* dic=[NSJSONSerialization JSONObjectWithData:dataString options:NSJSONReadingMutableContainers error:nil];
            NSLog(@"%@",dic);
            NSString *filePath = [NSHomeDirectory() stringByAppendingString:[NSString stringWithFormat:@"/Documents/home_id%@_getcatedetail.json",self.currentSong.id]];
            if ([fileManager fileExistsAtPath:filePath]) {
                [fileManager removeItemAtPath:filePath error:nil];
            }
            [dataString writeToFile:filePath atomically:YES];
            self.dic=dic;
            [self upDateView];
        } andError:^(NSError * _Nonnull error) {
        }];
    }
}
/**刷新页面*/
-(void)upDateView
{
    NSLog(@"aaaaaaaaaa");
    NSArray* array=self.dic[@"data"][@"additional"];
    for(int i=0;i<array.count;i++)
    {
        if(i<self.btnArr.count)
        {
            UIButton* btn=self.btnArr[i];
            btn.alpha=1;
            [btn setTitle:array[i][@"title"] forState:UIControlStateNormal];
        }
    }
    [self cureePlayer];
    
    NSDictionary *dic = self.dic[@"data"];
    if ([dic.allKeys containsObject:@"introduce"]) {
        id introduce = self.dic[@"data"][@"introduce"];
        if (![introduce isNullObject]) {
            NSLog(@"%@",self.dic[@"data"][@"introduce"]);
            [self.wkwebView loadHTMLString:self.dic[@"data"][@"introduce"] baseURL:nil];
        }
    }
    
    /**刷新文字*/
    [self.playsubtitleView refreshUrl:self.dic[@"data"][@"srt"] andFileId:[NSString stringWithFormat:@"%@",self.dic[@"data"][@"id"]]];
    [self refreshPlayUI];

    self.tipLabel.text = [PlayModel sharedModel].currentModel.name;
}
-(void)refreshPlayUI
{
    [self.playBtn setBackgroundImage:[UIImage imageNamed:self.isplayer?@"播放":@"暂停"] forState:UIControlStateNormal];
}
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
    //禁止用户选择
    [webView evaluateJavaScript:@"document.documentElement.style.webkitUserSelect='none';" completionHandler:nil];
    [webView evaluateJavaScript:@"document.activeElement.blur();" completionHandler:nil];
    // 适当增大字体大小
    [webView evaluateJavaScript:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '300%'" completionHandler:nil];
}
-(void)removeView
{
    [_objectAFN cancelRequest];
    [_wkwebView removeFromSuperview];
    _wkwebView=nil;
    [self clearView];
}
-(void)clearView
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    if(_player)
    {
        [_player.currentItem cancelPendingSeeks];
        [_player.currentItem.asset cancelLoading];
        [_player replaceCurrentItemWithPlayerItem:nil];
        [_player removeTimeObserver:_infotu];
        _infotu=nil;
        _player=nil;
    }
    if(_item)
    {
        AVURLAsset *asset = (AVURLAsset *)_item.asset;
        [asset.resourceLoader setDelegate:nil queue:dispatch_get_main_queue()];
        _item=nil;
    }
    self.slider.value=0;
    self.tipLabel.text=@"";
    for (UIButton* btn in self.btnArr) {
        btn.alpha=0;
    }
    [_wkwebView removeFromSuperview];
    _wkwebView=nil;
    [self.playsubtitleView clearData];
    self.endLabel.text=@"";
    self.startLabel.text=@"";
}
- (void)remoteControlReceivedWithEvent:(UIEvent *)event
{
 
//     根据事件的子类型(subtype) 来判断具体的事件类型, 并做出处理
 
       switch (event.subtype)
       {
           case UIEventSubtypeRemoteControlPlay:
           
           case UIEventSubtypeRemoteControlPause: {
//
               [self playPlayer];
//           执行播放或暂停的相关操作 (锁屏界面和上拉快捷功能菜单处的播放按钮)
           
               break;
           }
           case UIEventSubtypeRemoteControlPreviousTrack: {
       
//           执行上一曲的相关操作 (锁屏界面和上拉快捷功能菜单处的上一曲按钮)
           
               break;
           }
           case UIEventSubtypeRemoteControlNextTrack: {
       
//           执行下一曲的相关操作 (锁屏界面和上拉快捷功能菜单处的下一曲按钮)
           
               break;
           }
           case UIEventSubtypeRemoteControlTogglePlayPause: {
       
//           进行播放/暂停的相关操作 (耳机的播放/暂停按钮)
               break;
           }
           default:
       
           break;
               
       }
}
-(void)btnAction:(UIButton*)sender
{
    if(sender.tag==400)
    {
        if(self.dic)
        {
            self.backView.alpha=!self.backView.alpha;
            [sender setImage:[UIImage imageNamed:self.backView.alpha?@"字幕关闭":@"字幕开启"] forState:UIControlStateNormal];
            self.playsubtitleView.alpha=!self.backView.alpha;
        }else
        {
            [GC_OCTool startTishil:@"正在请求数据..."];
        }
    }else if(sender.tag==401)/**定时器*/{
        
    }else if(sender.tag==402)/**倍速*/{
        PlayMulitpleView *view = [[PlayMulitpleView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        view.mulitBlock = ^(NSString * _Nonnull mulit) {
            
        };
        
        UIView *superView = UIApplication.sharedApplication.keyWindow.rootViewController.view;
        if (!superView) {
            superView = [UIApplication sharedApplication].keyWindow;
        }
        [view showIn:superView];
    }
}

- (void)lastBtnAction:(UIButton*)sender
{
    if(sender.tag == 600)
    {
        [[PlayModel sharedModel] changePlayStyle];
        NSArray* user = @[@"循环播放",@"单曲播放",@"随机播放"];
        [sender setBackgroundImage:[UIImage imageNamed:user[[PlayModel sharedModel].playStyle]] forState:UIControlStateNormal];
    }else if(sender.tag==601)
    {
        [self previousPlayer];
    }else if(sender.tag==602)
    {
        self.isplayer=!self.isplayer;
        if(self.isplayer)
        {
            [self playPlayer];
        }else
        {
            [self stopPlayer];
        }
    }else if(sender.tag==603)
    {
        [self nextPlayer];
    }else if(sender.tag==604)
    {
        
    }
}


- (CurriculumModel *)currentSong {
    return [PlayModel sharedModel].currentModel;
}

- (void)dealloc {
    NSLog(@"PlayVoiceView dealloc");
}
@end
